package com.info.zhiduoduo.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.info.zhiduoduo.common.aliyunsdk.RecognizeIdcardService;
import com.info.zhiduoduo.common.annotation.LogEntity;
import com.info.zhiduoduo.common.annotation.ZddLog;
import com.info.zhiduoduo.common.baidusdk.domain.OcrIdcardResult;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.system.ZddLogType;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.formbean.ImgDataFormBean;
import com.info.zhiduoduo.common.utils.*;
import com.info.zhiduoduo.core.formbean.BankCardElementFormBean;
import com.info.zhiduoduo.core.service.CommonService;

import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.common.DianDianYunService;
import com.info.zhiduoduo.core.service.impl.BankCardElementCertificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/common")
public class CommonController {

	@Autowired
	UploadPathConfig uploadPathConfig;

	@Autowired
	ResourceLoader  resourceLoader;

	@Autowired
	CommonService commonService;

	@Autowired
	DianDianYunService dianDianYunService;

	@Autowired
	BankCardElementCertificationService bankCardElementCertificationService;

	@Autowired
	WxMessageService wxMessageService;

	/**
	 * 生成新的 截图   上传base64的数据
	 *
	 * @param beanBaseSimpleFormBean
	 */
	@RequestMapping(value = "/saveSnapshot", method = RequestMethod.POST)
	@ResponseBody
	public SmartResult saveSnapshot(@RequestBody BaseSimpleFormBean<ImgDataFormBean> beanBaseSimpleFormBean) {

		SmartResult smartResult = new SmartResult();

		ImgDataFormBean imgDataFormBean = beanBaseSimpleFormBean.getReqdata();

		if (null != imgDataFormBean && !StringUtil.isEmpty(imgDataFormBean.getImgdata())) {
			String imgdata = imgDataFormBean.getImgdata();
			imgdata = imgdata.substring(imgdata.indexOf("base64,") + 7);

			String oss_object = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);
			String fileName = UUID.randomUUID().toString() + ".png";

			//物理地址
			String imgFilePath = uploadPathConfig.getUploadpath() + "/" + oss_object + "/" + fileName;
			File file = ImgBase64Util.Base64ToImg(imgdata, imgFilePath);

			//String imgpath = OssHelper.imgUploadOss(uploadPath,imgDataFormBean.getImgdata());

			smartResult.setObject(oss_object + "/" + fileName);
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_102);
		}
		return smartResult;
	}

	/**
	 * 图片文件上传
	 *
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/uploadImgFile", method = RequestMethod.POST)
	@ResponseBody
	public SmartResult uploadImgFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "type", defaultValue = "0") int type) {
		SmartResult smartResult = new SmartResult();
		if (!file.isEmpty()) {
			try {
				smartResult.setObject(saveImg2Local(file));
			} catch (Exception e) {
				e.printStackTrace();
				smartResult.setStateMsg(StatusMsg.StatusMsg_198);
				return smartResult;
			}
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_102);
			return smartResult;
		}

		return smartResult;
	}

	@ZddLog(name = "上传身份证并通过点点云认证")
	@ApiOperation("上传身份证并通过点点云认证")
	@RequestMapping(value = "/uploadIdCardByDianDianYun", method = RequestMethod.POST)
	public SmartResult uploadIdCardByDianDianYun(@RequestParam("file") MultipartFile file,@RequestParam(value = "type") int type) {

		if (!file.isEmpty()) {
			try {
				String path = saveImg2Local(file);
				//根据类型确定身份证正反面，确定传入参数
//				String idCardSide = "";
//				if (1 == type) {
//					idCardSide = "front";
//				} else {
//					idCardSide = "back";
//				}
//				Map<String, Object> map = dianDianYunService.idCardAnalysis(uploadPathConfig.getUploadpath() + path, idCardSide);
				OcrIdcardResult result = RecognizeIdcardService.checkIdCard(new File(uploadPathConfig.getUploadpath() + path));
				if (result == null) {
					return SmartResult.fail("解析错误，请重新上传!");
				} else {
					return SmartResult.success(result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return SmartResult.fail(StatusMsg.StatusMsg_198);
			}

		} else {
			return SmartResult.fail(StatusMsg.StatusMsg_102);
		}
	}

	/**
	 * 图片文件上传,特殊格式要求
	 *
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/uploadImgFile2", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject uploadImgFile2(@RequestParam("file") MultipartFile file, @RequestParam(value = "type", defaultValue = "0") int type) {
		JSONObject result = new JSONObject();
		if (!file.isEmpty()) {
			try {
				JSONArray data = new JSONArray();
				data.add(saveImg2Local(file));
				result.put("errno", 0);
				result.put("data", data);
			} catch (Exception e) {
				e.printStackTrace();
				result.put("errno", StatusMsg.StatusMsg_198.getState());
			}
		} else {
			result.put("errno", StatusMsg.StatusMsg_102.getState());
		}

		return result;
	}

	private String saveImg2Local(MultipartFile file) throws IOException {
		//文件夹名
		String fileFolder = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);

		String uploadPath = uploadPathConfig.getUploadpath();
		File filePath = new File(uploadPath + "/" + fileFolder);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		String imgFile = RandomUtil.createRandomNo("img_", ".png");
		String path = uploadPath + "/" + fileFolder + "/" + imgFile;
		File uploadFile = new File(path);
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(uploadFile));
		out.write(file.getBytes());
		out.flush();
		out.close();

		return fileFolder + "/" + imgFile;
	}

	@ApiOperation("上传文件")
	@PostMapping(value = "/uploadFile")
	public SmartResult uploadFile(@RequestParam("file") MultipartFile file) {
		SmartResult smartResult = new SmartResult();
		String filePath = FileUtil.uploadFile(uploadPathConfig.getUploadpath(), file);
		if (StringUtil.isEmpty(filePath)) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_199);
		}
		smartResult.setObject(filePath);
		return smartResult;
	}

	/**
	 * 通用的获取文件的方法 匹配的 文件路径拼接在"/get/imgfile"后面. 如
	 * <p>
	 * /get/imgfile/img/img_2018050925284568.jpg
	 * <p>
	 * /get/imgfile/qrcode/qr_2018051030597792.jpg
	 *
	 * @param request
	 * @param filename
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/get/imgfile/**/{filename:.+}")
	@ResponseBody
	public ResponseEntity<?> getFile(HttpServletRequest request, @PathVariable String filename) {
		String requestURI = request.getRequestURI();
		LogUtil.info(requestURI);
		try {
			String uploadpath = uploadPathConfig.getUploadpath();
			LogUtil.info(uploadpath);
			String filePath = requestURI.replaceFirst("/common/get/imgfile", "");
			Resource resource = resourceLoader.getResource("file:" + Paths.get(uploadpath, filePath).toString());
			return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).contentLength(resource.contentLength()).body(new InputStreamResource(resource.getInputStream()));
		} catch (Exception e) {
			LogUtil.info("获取文件出错");
			return ResponseEntity.notFound().build();
		}
	}

	/**
	 * 下载二维码
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@GetMapping(value = "/downloadImgFile/**/{filename:.+}")
	public ResponseEntity<?> downloadQrcode(HttpServletRequest request,
	HttpServletResponse response, @PathVariable String filename) throws Exception {
		String uri = request.getRequestURI();
		if (StringUtil.isEmpty(uri)) {
			return ResponseEntity.notFound().build();
		}
		LogUtil.info("uri = " + uri);
		String filePath = uri.replaceFirst("/common/downloadImgFile", "");

		BufferedInputStream bis = null;
		OutputStream outputStream = null;

		response.setContentType(MediaType.valueOf("application/force-download").getType());
		response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(filename, "utf-8"));

		try {
			outputStream = response.getOutputStream();
			//待下载文件的路径
			File file = new File(uploadPathConfig.getUploadpath(), filePath);
			bis = new BufferedInputStream(new FileInputStream(file));

			byte[] buff = new byte[1024];
			while (bis.read(buff) != -1) {
				outputStream.write(buff, 0, buff.length);
			}
			return ResponseEntity.ok().body(bis);

		} catch (IOException e) {
			e.printStackTrace();
			return ResponseEntity.notFound().build();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/*
	 * @param ips  输入流
	 * @param ops  输出流
	 * @param closeStream  是否关闭流
	 * @throws Exception
	 */
	private static void copyStream(InputStream ips, OutputStream ops, boolean closeStream) throws Exception {
		byte[] buf = new byte[1024];
		int len = ips.read(buf);
		while (len != -1) {
			ops.write(buf, 0, len);
			len = ips.read(buf);
		}
	}

	@ApiOperation("验证银行卡信息")
	@GetMapping("validateCardInfo")
	public SmartResult validateCardInfo(@RequestParam("cardNo") String cardNo) {
		return commonService.validateCardInfo(cardNo);
	}

	@ApiOperation("银行卡要素认证")
	@PostMapping(value = "/bankCardElementCertification")
	public SmartResult bankCardElementCertification(@RequestBody BankCardElementFormBean formBean) {
		JSONObject result = bankCardElementCertificationService.postBankCardElement(formBean);
		return SmartResult.success(result.getInteger("result"));
	}

	@ApiOperation("创客消息通知")
	@GetMapping("/makerMessageNotification")
	public SmartResult makerMessageNotification(@RequestParam("userId") int userId,
											    @RequestParam("content") String content) {
		if (!wxMessageService.makerMessageNotification(userId,content)){
			return SmartResult.fail();
		}
		return SmartResult.success();
	}
}